import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * @author ganbo
 * @date 2022/12/2 13:43
 */

@Slf4j
public class CClient {


    public static void main(String[] args) throws InterruptedException {

        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));   //完善netty日志打印
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect("127.0.0.1", 8888);

        ChannelFuture sync = channelFuture.sync();
        new Thread(() -> {
            Channel channel = sync.channel();
            Scanner scanner = new Scanner(System.in);
            while (true) {
                log.info("请输入内容=====>");
                String s = scanner.nextLine();
                if ("q".equals(s)) {
                    ChannelFuture close = channel.close();
                    break;
                } else {
                    channel.writeAndFlush(s);
                }
            }
        }).start();

        ChannelFuture closeFuture = channelFuture.channel().closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("关闭回调方法");
                System.out.println("future==================>" + future);
                System.out.println("sucess ==============>" + future.isSuccess());

                //优雅关闭
                group.shutdownGracefully();
                System.out.println("优雅关闭结束");
            }
        });

    }
}
